<template>
  <div class="queryform-container">
    <a-form ref="queryFormRef" :model="queryForm" layout="inline">
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="用户名"
                   name="username">
        <a-input v-model:value="queryForm.username" allow-clear/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button class="split-button" type="primary" @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
  <div class="action-buttons-container">
    <a-button class="split-button" type="primary" @click="handleOpenAddModel(false)">新增</a-button>
    <a-button class="split-button" type="primary" :disabled="!singleSelect" @click="handleOpenAddModel(true)">修改
    </a-button>
    <a-popconfirm
        title="确定删除这条记录?"
        ok-text="确定"
        cancel-text="取消"
        @confirm="handleDelete(null)"
        :disabled="!singleSelect"
    >
      <a-button :disabled="!singleSelect" class="split-button" type="danger">删除</a-button>
    </a-popconfirm>
  </div>
  <a-table rowKey="id" :row-selection="rowSelection" :data-source="sysUserList" :columns="columns">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-popconfirm title="确定还原密码?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="handleRestPassword(record)">
          <a-button type="primary">还原密码</a-button>
        </a-popconfirm>
      </template>
      <template v-if="column.key === 'avatarFileHash'">
        <img v-if="record.avatarFileHash" style="width:40px;height:40px;" :src="`/api/system/avatar/preview?file=${record.avatarFileHash}&Authorization=${getToken()}`"/>
        <span v-else>--</span>
      </template>
    </template>
  </a-table>
  <a-modal v-model:visible="showAddModel" title="新增或修改用户" @ok="handleSave">
    <a-form ref="addFormRef" :model="sysUserForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }" autocomplete="off">
      <a-form-item style="display: none;"
                   label="id"
                   name="id">
        <a-input v-model:value="sysUserForm.id"/>
      </a-form-item>
      <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名!' }]"
      >
        <a-input v-model:value="sysUserForm.username"/>
      </a-form-item>
      <a-form-item
          label="昵称"
          name="nickname"
          :rules="[{ required: true, message: '请输入昵称!' }]"
      >
        <a-input v-model:value="sysUserForm.nickname"/>
      </a-form-item>
      <a-form-item
          label="邮箱地址"
          name="mailAddress"
          :rules="[{ required: false, message: '请输入邮箱地址!' }]"
      >
        <a-input v-model:value="sysUserForm.mailAddress"/>
      </a-form-item>
      <a-form-item
          label="部门"
          name="deptCode"
          :rules="[{ required: false, message: '请选择部门' }]"
      >
        <a-tree-select
            v-model:value="sysUserForm.deptCode"
            :fieldNames="{children:'children', label:'deptName', value: 'deptCode' }"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder=""
            allow-clear
            tree-default-expand-all
            :tree-data="deptSelectTreeData"
        >
        </a-tree-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import request, {getToken} from "@/util/request.js";
import {message} from 'ant-design-vue';
import {nextTick, onMounted, reactive, ref} from "vue";
import {showLoading,hideLoading, validValue} from "@/util/util.js";

const queryFormRef = ref(null);
const addFormRef = ref(null);
let showAddModel = ref(false)
let sysUserList = ref([]);
let columns = [{
  title: '用户名',
  dataIndex: 'username',
  key: 'username'
}, {
  title: '昵称',
  dataIndex: 'nickname',
  key: 'nickname'
}, {
  title: '头像',
  dataIndex: 'avatarFileHash',
  key: 'avatarFileHash'
}, {
  title: '邮箱地址',
  dataIndex: 'mailAddress',
  key: 'mailAddress'
}, {
  title: '部门',
  dataIndex: 'deptName',
  key: 'deptName'
},{
  title: '最近登录时间',
  dataIndex: 'lastLoginTime',
  key: 'lastLoginTime'
},  {
  title: '操作',
  key: 'action',
},]
let sysUserForm = ref({id: null, username: '', password: null, mailAddress: ''})
let selectedRows = ref([])
let singleSelect = ref(false)
onMounted(() => {
  query({})
})
let rowSelection = {
  onChange: (selectedRowKeys, _selectedRows) => {
    selectedRows.value = _selectedRows
    singleSelect.value = selectedRowKeys && selectedRowKeys.length === 1;
  },
  // getCheckboxProps: record => ({
  //   disabled: record.name === 'Disabled User',
  //   // Column configuration not to be checked
  //   name: record.name,
  // }),
}
let queryForm = ref({username: null})
let handleQuery = () => {
  query(queryForm.value)
}
let handleReset = () => {
  queryFormRef.value.resetFields()
}
let query = (param) => {
  showLoading()
  request({
    method: 'post',
    url: '/api/system/sysUser/query',
    data: param || {}
  }).then((res) => {
    sysUserList.value = res.data
    hideLoading()
  })
}

let handleOpenAddModel = (editing) => {
  showAddModel.value = true
  sysUserForm.value = {}
  loadDeptSelectTree();
  if (editing) {
    //加载明细
    let selectedRow = selectedRows.value[0];
    sysUserForm.value = {...selectedRow};
  }
}

let handleSave = () => {
  addFormRef.value.validate().then((res) => {
    showLoading()
    request({
      method: 'post',
      url: '/api/system/sysUser/saveOrUpdate',
      data: res
    }).then((res) => {
      hideLoading()
      if (res.code === 200) {
        showAddModel.value = false;
        message.success("保存成功")
        query();
      } else {
        message.error("操作失败" + res.errMsg)
      }
    })
  }).catch(() => {
    hideLoading()
  })
}
const deptSelectTreeData = ref([]);

function loadDeptSelectTree() {
  request({
    method: 'post',
    url: '/api/system/dept/loadDeptTree',
  }).then((response) => {
    let root = response.data
    deptSelectTreeData.value = root
  })
}

function handleDelete(row) {
  if (!validValue(row)) {
    console.log(selectedRows.value)
    row = selectedRows.value[0];
  }
  showLoading()
  request({
    method: 'delete',
    url: '/api/system/sysUser/deleteById',
    params: {id: row.id}
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('删除成功');
      handleQuery()
    } else {
      message.error("删除失败：" + res.errMsg)
    }
  })
}

function handleRestPassword(row) {
  showLoading()
  request({
    method: 'post',
    url: '/api/system/sysUser/resetPassword?userId=' + row.id,
  }).then((res) => {
    hideLoading()
    if (res.code === 200) {
      message.info('操作成功');
    } else {
      message.error("操作失败：" + res.errMsg)
    }
  })
}
</script>
<style scoped>

</style>
